package com.ruoyi.framework.listener;

import com.ruoyi.common.exception.ServiceException;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class AuthenticationFailureListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {

    protected static Map<String, Integer> passwordErrorCount = new HashMap<>();

    public static Map<String, Date> validityTimeMap = new HashMap<>();
    @Value("${ruoyi.validityTime}")
    private Integer validityTime;
    @Value("${ruoyi.allErrorCount}")
    private Integer allErrorCount;

    @Override
    public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
        String username = event.getAuthentication().getPrincipal().toString();
        if(validityTimeMap.containsKey(username)){
            throw new ServiceException("密码输入多次错误,账号将被锁定"+validityTime+"分钟");
        }

        // 判断密码错误集合是否包含此账号
        if (passwordErrorCount.containsKey(username)) {
            Integer count = passwordErrorCount.get(username);
            // 判断密码错误次数大于N-1次(允许的错误次数-1)
            if(count>=(allErrorCount-1)){
                // 该账号将被锁定10分钟,限制登陆
                validityTimeMap.put(username, DateUtils.addMinutes(new Date(),validityTime));
            }else{
                passwordErrorCount.put(username,++count);
            }
        }else{
            // 密码错误次数+1
            passwordErrorCount.put(username,1);
        }



    }
}
